import { defineStore } from 'pinia'
import { getUserInfo, getUserMenuList, logout } from '@/api/user'
import { GET_TOKEN, REMOVE_TOKEN } from '@/plugins/util'
import useUnitStore from '@/stores/unit'
import router from '@/router'
import useRoleStore from '@/stores/role'
import useDictionaryStore from '@/stores/dictionary'
import useLeaderStore from '@/stores/leader'

const modules = import.meta.glob('@/views/**/*.vue')

const roleStrLength = 3
const permissionStrLength = 4

interface User {
  id: number
  isAdmin: number
  name: string
  phone: string
  satoken: string
  unitId: number
  unitName: string
  departmentId: number
  departmentName: string
  userName: string
  first: boolean
  permissionList: string[]
  permissionRoleList: string[]
  menuTree: any[]
}

export const useUserStore = defineStore('User', {
  state: (): User => ({
    id: null,
    isAdmin: null,
    name: '',
    phone: '',
    satoken: GET_TOKEN(),
    unitId: null,
    unitName: '',
    departmentId: null,
    departmentName: '',
    userName: '',
    first: false,
    permissionList: [],
    permissionRoleList: [],
    menuTree: [],
  }),
  actions: {
    async getUserInfoToStore() {
      const { data } = await getUserInfo()
      if (data.status === 200) {
        this.id = data.data.id
        this.userName = data.data.userName
        this.name = data.data.name
        this.phone = data.data.phone
        this.unitId = data.data.unitId
        this.unitName = data.data.unitName
        this.departmentId = data.data.departmentId
        this.departmentName = data.data.departmentName
        this.first = data.data.first
        this.permissionList = data.data.permissionList
        this.permissionRoleList = data.data.permissionRoleList
        this.isAdmin = data.data.isAdmin

        const unitStore = useUnitStore()
        unitStore.getUnit()

        const leaderStore = useLeaderStore()
        leaderStore.getLeader()

        const roleStore = useRoleStore()
        roleStore.getRole()

        await this.setRoute()
        return 2
      }
      return 0
    },
    async setRoute() {
      const { data } = await getUserMenuList(this.id)
      if (data.status === 200) {
        addRouter(data.data)
        this.menuTree = data.data
      }
    },
    async checkUser() {
      if (this.userName) {
        return 1
      }
      return await this.getUserInfoToStore()
    },
    /**
     * 获取一般权限id
     * 业务规定一般权限一定是数值
     * @param permissionText 权限标识符
     */
    getPermissionId(permissionText: string): number[] {
      if (this.isAdmin === 1) {
        const unitStore = useUnitStore()
        return unitStore.list.map((item) => item.id)
      } else {
        const ids: number[] = []
        for (const permission of this.permissionList) {
          if (permission.indexOf(permissionText) > -1) {
            const tempArray = permission.split(':')
            const id = tempArray[tempArray.length - 1]
            if (Number(id)) {
              ids.push(+id)
            }
          }
        }
        return ids
      }
    },
    /**
     * 判断是否有一般权限
     * 业务规定一般权限一定是数值
     * @param permissionText 权限标识符
     */
    hasPermission(permissionText: string) {
      return this.isAdmin || this.getPermissionId(permissionText).length !== 0
    },
    /**
     * 获取默认的unitId
     * @param permissionText 权限标识符
     * @returns 默认的unitId
     */
    getDefaultUnitId(permissionText: string): number {
      if (this.isAdmin === 1) {
        return this.unitId
      } else {
        const ids = this.getPermissionId(permissionText)
        if (ids.length !== 0) {
          if (ids.includes(this.unitId)) {
            return this.unitId
          } else {
            return ids[0]
          }
        } else {
          return undefined
        }
      }
    },
    /**
     * 获取全部权限id
     * @param permissionText 权限标识符
     */
    getAllPermissionId(permissionText: string) {
      const ids = []
      for (const permission of this.permissionList) {
        if (permission.indexOf(permissionText) > -1) {
          const tempArray = permission.split(':')
          const id = tempArray[tempArray.length - 1]
          ids.push(id)
        }
      }
      return ids
    },
    /**
     * 判断是否有任意权限（一般或特殊）
     * @param permissionText 权限标识符
     */
    hasAnyPermission(permissionText: string) {
      return (
        this.isAdmin || this.getAllPermissionId(permissionText).length !== 0
      )
    },
    /**
     * 获取特殊权限id
     * 业务规定特殊权限一定不是数值
     * @param permissionText 权限标识符
     */
    getSpecialPermissionId(permissionText: string) {
      const ids = []
      for (const permission of this.permissionList) {
        if (permission.indexOf(permissionText) > -1) {
          const tempArray = permission.split(':')
          const id = tempArray[tempArray.length - 1]
          if (!Number(id)) {
            ids.push(id)
          }
        }
      }
      return ids
    },
    /**
     * 判断是否有特殊权限
     * 业务规定特殊权限一定不是数值
     * @param permissionText
     */
    hasSpecialPermission(permissionText: string) {
      return (
        this.isAdmin || this.getSpecialPermissionId(permissionText).length !== 0
      )
    },
    /**
     * 根据权限获取角色标识符
     * @param permissionText
     */
    getRoleCodeByPermission(permissionText: string) {
      const roleCodeList: string[] = []
      for (const permission of this.permissionRoleList) {
        if (permission.includes(`${permissionText}`)) {
          const tempArray = permission.split(':')
          if (tempArray.length === permissionStrLength) {
            const roleCode = tempArray[tempArray.length - 1]
            roleCodeList.push(roleCode)
          }
        }
      }
      return roleCodeList
    },
    /**
     * 判断是否有角色标识符
     * @param permissionText 权限标识符
     * @param roleCode 角色标识符
     */
    hasRoleCodeByPermission(
      permissionText: string,
      roleCode: string | string[],
    ) {
      if (this.isAdmin) {
        return true
      }
      if (Array.isArray(roleCode)) {
        return roleCode.some((item) =>
          this.getRoleCodeByPermission(permissionText).some(
            (roleStr: string) => {
              const tempArray = roleStr.split(':')
              return (
                tempArray.length === roleStrLength &&
                tempArray[tempArray.length - 1] === item
              )
            },
          ),
        )
      } else {
        return this.getRoleCodeByPermission(permissionText).some(
          (roleStr: string) => {
            const tempArray = roleStr.split(':')
            return (
              tempArray.length === roleStrLength &&
              tempArray[tempArray.length - 1] === roleCode
            )
          },
        )
      }
    },
    /**
     * 判断是否有角色标识符
     * @param roleCode 角色标识符
     */
    hasRoleCode(roleCode: string | string[]) {
      if (this.isAdmin) {
        return true
      }
      if (Array.isArray(roleCode)) {
        return roleCode.some((item) =>
          this.permissionRoleList.some((roleStr: string) => {
            const tempArray = roleStr.split(':')
            return (
              tempArray.length === roleStrLength &&
              tempArray[tempArray.length - 1] === item
            )
          }),
        )
      } else {
        return this.permissionRoleList.some((roleStr: string) => {
          const tempArray = roleStr.split(':')
          return (
            tempArray.length === roleStrLength &&
            tempArray[tempArray.length - 1] === roleCode
          )
        })
      }
    },
    // 是否有该权限
    isRolePermission(rolePermission: string[]) {
      if (!rolePermission?.length) return false
      if (this.isAdmin) return true
      return this.permissionRoleList.some((rolePermissionItem) =>
        rolePermission.includes(rolePermissionItem),
      )
    },
    async logout() {
      const { data } = await logout()
      if (data.status === 200) {
        this.id = null
        this.isAdmin = null
        this.name = null
        this.phone = null
        this.unitId = null
        this.unitName = null
        this.departmentId = null
        this.departmentName = null
        this.userName = null
        this.first = null
        this.satoken = null
        this.menuTree = []
        this.permissionRoleList = []
        this.permissionList = []
        REMOVE_TOKEN()
        this.resetOtherStore()
        location.href = `${import.meta.env.BASE_URL}/login`
      }
    },
    clearUser() {
      this.$reset()
    },
    resetOtherStore() {
      useUnitStore().reset()
      useRoleStore().reset()
      useDictionaryStore().reset()
    },
    // 是否有审核权限
    hasApprovePermission(userId: number) {
      return userId === this.id
    },
  },
  getters: {},
})

function addRouter(menuTree: any, basePath = '') {
  for (const menu of menuTree) {
    if (menu.menuType === 'M' && menu.children) {
      addRouter(menu.children, `${basePath}${menu.path}`)
    } else if (menu.menuType === 'C') {
      const newRoute = {
        id: menu.id,
        path: `${basePath}${menu.path}`,
        component: modules[`/src/views${menu.component}.vue`],
        meta: {
          title: menu.name,
          icon: menu.icon,
          hidden: menu.hidden === 1,
          perms: menu.perms,
        },
      }
      router.addRoute(newRoute)
    }
  }
}

export default useUserStore
